# Bullet.gd
class_name Bullet
extends CharacterBody2D

# 子弹属性
@export var speed: float = 800.0
@export var damage: int = 10
@export var lifetime: float = 1.0
@export var penetration: bool = false

# 内部变量
var direction: Vector2    = Vector2.RIGHT
var time_alive: float     = 0.0
var has_hit: bool         = false
var hit_count: int        = 0  # 记录击中次数，用于限制穿透次数
var max_penetrations: int = 3  # 最大穿透次数

# 组件引用
@onready var collision_shape: CollisionShape2D = $CollisionShape2D
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
# 信号
signal hit_enemy(enemy, bullet, damage)
signal hit_object(object, bullet)


func _ready() -> void:
	add_to_group("bullets")

	# 播放动画
	if animated_sprite:
		animated_sprite.play("default")

	# 设置初始方向和速度
	velocity = direction * speed

	# 根据方向设置旋转
	rotation = direction.angle()


func _physics_process(delta: float) -> void:
	# 更新生存时间
	time_alive += delta
	if time_alive >= lifetime:
		queue_free()
		return

	# 移动子弹
	velocity = direction * speed
	var _collision = move_and_slide()

	# 处理碰撞
	if get_slide_collision_count() > 0:
		handle_collision()


# 设置子弹方向
func set_direction(new_direction: Vector2) -> void:
	direction = new_direction.normalized()
	rotation = direction.angle()


# 处理碰撞
# 处理碰撞
func handle_collision() -> void:
	if has_hit:
		return

	has_hit = true

	for i in get_slide_collision_count():
		var collision: KinematicCollision2D = get_slide_collision(i)
		var collider: Object                = collision.get_collider()

		# 确保 collider 不为空并且是 Node 类型
		if collider == null:
			continue

		if not (collider is Node):
			emit_signal("hit_object", collider, self)
			destroy()
			return

		# 现在可以安全地调用 is_in_group
		# 检查是否碰到敌人
		collider = collider as Node
		if collider.is_in_group("enemies") and collider.has_method("take_damage"):
			# 计算实际伤害，可以根据距离或其他因素调整
			var actual_damage = calculate_damage(collider)
			collider.take_damage(actual_damage)
			emit_signal("hit_enemy", collider, self, actual_damage)

			# 如果不能穿透，或已达到最大穿透次数，销毁子弹
			hit_count += 1
			if not penetration or hit_count >= max_penetrations:
				destroy()
				return

			# 检查是否碰到其他物体
		elif collider.is_in_group("player") == false and collider.is_in_group("bullets") == false:
			emit_signal("hit_object", collider, self)
			destroy()
			return

	# 重置碰撞标志，允许检测下一次碰撞
	has_hit = false


# 根据距离和其他因素计算实际伤害
func calculate_damage(_target) -> int:
	# 基础伤害
	var actual_damage: int = damage

	# 这里可以添加距离衰减或暴击等机制
	# 例如：
	# var distance = global_position.distance_to(target.global_position)
	# actual_damage = int(damage * (1.0 - min(distance / 500.0, 0.7)))

	return max(1, actual_damage)  # 确保至少造成1点伤害


# 销毁子弹
func destroy() -> void:
	# 禁用碰撞
	collision_shape.set_deferred("disabled", true)

	# 如果有impact动画，播放它
	if animated_sprite and animated_sprite.sprite_frames.has_animation("impact"):
		animated_sprite.play("impact")
		await animated_sprite.animation_finished
		queue_free()
	else:
		# 直接销毁
		queue_free()
